package org.xenon.vote.controller;

import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.xenon.vote.model.pojo.po.Ballot;
import org.xenon.vote.model.pojo.vo.Result;
import org.xenon.vote.service.BallotService;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RestController
@Validated
@RequestMapping("/workbench")
public class WorkbenchController {
    private final BallotService ballotService;

    public WorkbenchController(BallotService ballotDao) {
        this.ballotService = ballotDao;
    }

    /**
     * 搜索一个投票
     * @param msg 搜索信息 (模糊搜索)
     */
    @PostMapping("/search")
    public Result search(String msg, HttpServletRequest req) {
        class Res{
            int id;
            String name;
            String description;
            Date bir;
            public Res(int id, String name, String description, Date bir) {
                this.id = id;
                this.name = name;
                this.description = description;
                this.bir = bir;
            }

            public int getId() {
                return id;
            }

            public void setId(int id) {
                this.id = id;
            }

            public String getName() {
                return name;
            }

            public void setName(String name) {
                this.name = name;
            }

            public String getDescription() {
                return description;
            }

            public void setDescription(String description) {
                this.description = description;
            }

            public Date getBir() {
                return bir;
            }

            public void setBir(Date bir) {
                this.bir = bir;
            }
        }
        String mail = (String) req.getSession().getAttribute("user");
        if (mail == null) return new Result(false, "login");
        List<Ballot> list = ballotService.getAll(mail, msg);
        List<Res> resList = new ArrayList<>();
        for (Ballot b : list)
            resList.add(new Res(b.getId(), b.getName(), b.getDescription(), b.getBirth()));
        return new Result(true, resList);
    }
}
